/* @file StickyHand.Java Graphical User Perspective
 * @author Jay Schulist jjschlst@gmail.com
 * 
 * Copyright (C) 2007 Jay Schulist
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package stickyhand.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;

import org.jdom.Attribute;

import stickyhand.NZB;

import com.apple.eawt.Application;
import com.apple.eawt.ApplicationEvent;
import com.apple.eawt.ApplicationListener;

public class StickyHand extends WindowAdapter implements ApplicationListener {
	final static public String name		= "StickyHand";
	final static public String version 	= "0.0.2";
	final static public String maintain	= "Jay Schulist <jjschlst@gmail.com>";
	final static public String web		= "http://code.google.com/p/stickyhand/";
	
	private JFrame main 		= null;
	private SHMenuBar menuBar	= null;
	private JToolBar toolBar	= null;
	private boolean onMacOSX	= false;
	private SHJList list		= null;
	private Application SHapp	= null;
	
	public StickyHand() throws Exception {		
		if (System.getProperty("mrj.version") != null)		/* detect if on MacOSX. */                                     
			onMacOSX = true;
		if (onMacOSX) {
			System.setProperty("apple.laf.useScreenMenuBar", "true");
			System.setProperty("apple.awt.showGrowBox", "true");
			System.setProperty("com.apple.mrj.application.growbox.intrudes", "fasle");
			System.setProperty("apple.awt.antialiasing", "true");
			System.setProperty("apple.awt.textantialiasing", "true");
			System.setProperty("com.apple.mrj.application.apple.menu.about.name", "StickyHand");
		}
		
		SHapp = new com.apple.eawt.Application();
	    SHapp.addApplicationListener(this);
	    SHapp.setEnabledPreferencesMenu(false);
		
		main = new JFrame();
		createFrame(main);
		main.setVisible(true);
	}
	
	/** Returns an ImageIcon, or null if the path was invalid. */
	protected static ImageIcon createImageIcon(String path, String description) {
	    java.net.URL imgURL = StickyHand.class.getResource(path);
	    if (imgURL != null) {
	        return new ImageIcon(imgURL, description);
	    } else {
	        System.err.println("Couldn't find file: " + path);
	        return null;
	    }
	}
	
	private void createFrame(JFrame fr) {		
		fr.setLayout(new BorderLayout());
		fr.setSize(400, 400);
		fr.setPreferredSize(new Dimension(400, 400));
		fr.setTitle("StickyHand");
		
		/* menu bar */
		menuBar = new SHMenuBar(this);
		fr.setJMenuBar(menuBar);
		
		/* tool bar */
		toolBar = new SHToolBar(this);
		fr.add(toolBar, BorderLayout.PAGE_START);
		
		/* status bar */
		fr.add(Box.createVerticalStrut(15), BorderLayout.SOUTH);
		
		/* contents. */
		list = new SHJList();
		list.addMouseListener(new MouseListener() {

			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() != 2)
					return;
				SHJList o = (SHJList)e.getSource();
				if (o.getSelectedIndex() < 0)
					return;
				DefaultListModel mod = (DefaultListModel)o.getModel();
				SHFileItem fileItem = (SHFileItem)mod.getElementAt(o.getSelectedIndex());
				JDialog info = new SHGetInfo(main, fileItem.nzb);
			}

			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			public void mousePressed(MouseEvent e) {
				
			}

			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		JScrollPane scroll = new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		fr.add(scroll, BorderLayout.CENTER);
		fr.pack();
	}
	
	public Action actionOpen = new AbstractAction() {
		public void actionPerformed(ActionEvent e) {
			FileDialog fileWin = new FileDialog(main, "Open NZB file", FileDialog.LOAD);
			fileWin.setVisible(true);
			
			File selFile = new File(fileWin.getDirectory() + "/" + fileWin.getFile());
			try {
				NZB nzb = new NZB(selFile, true);
				System.out.println("name: " + nzb.getName() + " size: " + nzb.getBytes());
				SHFileItem fi = new SHFileItem(nzb);
				DefaultListModel mod = (DefaultListModel)list.getModel();
				mod.addElement(fi);
			} catch(IOException io_ex) {
				
				// TODO: popup message saying invalid file or put into list, but mark as broken.
				io_ex.printStackTrace();
			}
		}
	};
	
	
	public Action actionQuit = new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				StickyHand.this.windowClosing(null);
			}
	};
	
	public Action actionMin = new AbstractAction() {
		public void actionPerformed(ActionEvent e) {
			main.setState(JFrame.ICONIFIED);
		}
	};
	
	public Action actionBringAllToFront = new AbstractAction() {
		public void actionPerformed(ActionEvent e) {
			main.setState(JFrame.NORMAL);
		}
	};
	
	/**
	 * Invoked when a window is in the process of being closed.
	 * The close operation can be overridden at this point.
	 */
	public void windowClosing(WindowEvent e) {
		super.windowClosing(e);
		System.exit(0);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int preload_jdom = Attribute.ENTITIES_TYPE;
		
		try {
			new StickyHand();
		} catch(Exception e) {
			// print error window here describing the problem.
			e.printStackTrace();
		}
		return;
	}

	public void handleAbout(ApplicationEvent event) {
		ImageIcon aboutIcon = this.createImageIcon("images/stickyhand.jpg", "StickyHand!");
		Image img = aboutIcon.getImage();
		
		float factor = 1.0f;
		if (img.getWidth(null) > img.getHeight(null))
			factor = Math.min(100f / img.getWidth(null), 1.0f);
		else
			factor = Math.min(100f / img.getHeight(null), 1.0f);
		Image scaledImage = img.getScaledInstance((int)(img.getWidth(null) * factor), 
				(int)(img.getHeight(null) * factor), Image.SCALE_FAST);
		aboutIcon.setImage(scaledImage);
		
		event.setHandled(true);
		JOptionPane.showMessageDialog(main, StickyHand.name + " release " + StickyHand.version + "\n"
				+ StickyHand.maintain + "\n"
				+ StickyHand.web + "\n\n" 
				+ "This software is licensed under the GNU General Public license\n"
				+ "http://www.gnu.org/copyleft/gpl.html\n",
				"About StickyHand", JOptionPane.INFORMATION_MESSAGE, aboutIcon);
	}

	public void handleOpenApplication(ApplicationEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void handleOpenFile(ApplicationEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void handlePreferences(ApplicationEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void handlePrintFile(ApplicationEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void handleQuit(ApplicationEvent arg0) {
		this.windowClosing(null);
	}

	public void handleReOpenApplication(ApplicationEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}
